Python Pandas DataFrame.to

您所在的位置:网站首页 html 表格颜色 Python Pandas DataFrame.to

Python Pandas DataFrame.to

#Python Pandas DataFrame.to| 来源: 网络整理| 查看: 265

本文主要介绍Python Pandas DataFrame.to_html方法使用示例代码,及使用CSS中class配置html的显示样式。

1、显示数据的示例代码

import pandas as pd import numpy as np pd.set_option('display.width', 1000) pd.set_option('colheader_justify', 'center') np.random.seed(6182018) demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50), 'analysis_tool': np.random.choice(['pandas', 'r', 'julia', 'sas', 'stata', 'spss'],50), 'database': np.random.choice(['postgres', 'mysql', 'sqlite', 'oracle', 'sql server', 'db2'],50), 'os': np.random.choice(['windows 10', 'ubuntu', 'mac os', 'android', 'ios', 'windows 7', 'debian'],50), 'num1': np.random.randn(50)*100, 'num2': np.random.uniform(0,1,50), 'num3': np.random.randint(100, size=50), 'bool': np.random.choice([True, False], 50) }, columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool'] ) print(demo_df.head(10)) # date analysis_tool num1 database num2 os num3 bool # 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True # 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False # 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False # 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False # 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True # 5 2018-04-05 sas -68.140295 sql server 0.346894 windows 10 0 True # 6 2018-05-07 julia 12.874660 postgres 0.195217 ios 79 True # 7 2018-01-22 r 189.410928 mysql 0.234815 windows 10 56 False # 8 2018-01-12 pandas -111.412564 sql server 0.580253 debian 30 False # 9 2018-04-12 r 38.963967 postgres 0.266604 windows 7 46 False

2、设置使用的CSS样式文件

另存为df_style.css

/* includes alternating gray and white with on-hover color */ .mystyle { font-size: 11pt; font-family: Arial; border-collapse: collapse; border: 1px solid silver; } .mystyle td, th { padding: 5px; } .mystyle tr:nth-child(even) { background: #E0E0E0; } .mystyle tr:hover { background: silver; cursor: pointer; }

3、DataFrame.to_html()方法使用及设置css样式代码

 

pd.set_option('colheader_justify', 'center') # FOR TABLE html_string = ''' HTML Pandas Dataframe with CSS {table} . ''' # OUTPUT AN HTML FILE with open('myhtml.html', 'w') as f: f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))

4、输出的html及显示效果

引用df_style.css,应该同一目录中;请参阅表中的类参数

HTML Pandas Dataframe with CSS date analysis_tool num1 database num2 os num3 bool 0 2018-04-21 pandas 153.474246 mysql 0.658533 ios 74 True 1 2018-04-13 sas 199.461669 sqlite 0.656985 windows 7 11 False 2 2018-06-09 stata 12.918608 oracle 0.495707 android 25 False 3 2018-04-24 spss 88.562111 sql server 0.113580 windows 7 42 False 4 2018-05-05 spss 110.231277 oracle 0.660977 windows 10 76 True ...

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3